package com.ciaojian.timer.task;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.config.FuluOpenConfig;
import com.ciaojian.core.constant.RedisConstant;
import com.ciaojian.core.enums.business.OrderStatusEnum;
import com.ciaojian.core.mapper.*;
import com.ciaojian.core.model.*;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.fulu.*;
import com.ciaojian.core.util.DateUtil;
import com.ciaojian.core.util.FuluUtil;
import com.ciaojian.core.util.JsonUtil;
import com.ciaojian.core.util.LogUtil;
import com.ciaojian.miniapp.api.WxMiniAppApi;
import com.ciaojian.miniapp.model.request.submessage.BaseTemplate;
import com.ciaojian.miniapp.model.request.submessage.TakeCouponMessage;
import com.ciaojian.miniapp.model.request.submessage.TakeHairTimeMessage;
import com.ciaojian.miniapp.model.request.submessage.TemplateIdEnum;
import com.ciaojian.miniapp.model.response.SubMessageSendResponse;
import com.ciaojian.timer.service.OrderServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Atlakyn
 */
@Component
public class AutoCancelOrderScheduled {
    @Resource
    private OrderServiceImpl orderService;
    @Resource
    private RedisTemplate<String, Integer> redisTemplate;
    @Resource
    private UserHairperiodMapper userHairperiodMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderMapper orderMapper;

    @Scheduled(cron = "${scheduled.cron.autoCancelOrderTask}")
    public void autoCancelOrder() {
        // 查询所有超过 8 小时的订单
        List<Order> orderList = orderService.findOrderTimeOut();
        orderList.forEach(order -> {
            order.setStatus(OrderStatusEnum.cancel);
            order.setCancelReason("自动取消");
            order.updateById();
            LogUtil.writeScheduleLog("订单:{%s}自动取消");
            // 丢进 Redis 缓存,等待读取
            redisTemplate.opsForSet().add(RedisConstant.AUTO_CANCEL_ORDER + order.getUserId(), order.getId());
        });
    }

    /**
     *
     */
    @Scheduled(cron ="0 0 17 * * ?")
    public void autoHairperTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        // 设置list大小 ,list一次行不能太多数据
        List<UserHairperiod> userHairperiodList = userHairperiodMapper.selectLists();
        for (UserHairperiod userHairperiod : userHairperiodList) {
            try {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(userHairperiod.getLastTime());
                calendar.add(Calendar.DAY_OF_MONTH, +userHairperiod.getTimelag());
                Date time = calendar.getTime();
                if (DateUtil.judgeTimeIsToday(time)) {
                    User user = userMapper.selectById(userHairperiod.getUserId());
                    Date date = orderMapper.selectFreshTime(user.getId());
                    String format = dateFormat.format(date);
                    Integer day = DateUtil.differentDays(date, new Date());
                    BaseTemplate baseTemplate = BaseTemplate.builder(TemplateIdEnum.AUDIT_HAIR_MESSAGE)
                            .touser(user.getOpenid())
                            .data(TakeHairTimeMessage.builder()
                                    .thing1("为了保持您的精致形象,建议来修剪造型哟~")
                                    .time2(format)
                                    .thing3(day.toString()+"天")
                                    .build()
                            );
                    try {
                        SubMessageSendResponse response = WxMiniAppApi.subscribeMessageSend(baseTemplate);
                        if (response.getErrcode() == 0) {
                            userHairperiod.setStatus(1);
                            userHairperiodMapper.updateById(userHairperiod);
                        } else {
                            LogUtil.writeBusinessLog("剪发提醒通知失败: {}", response.getErrmsg());
                        }
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                        LogUtil.writeErrorLog(e.getMessage());
                    }
                }
            } catch (Exception e) {

            }
        }
    }
}